<template>
	<view>
		<view class="flex align-center justify-center fs-28 pt-4 fte87722" v-if="auditText">{{auditText}}</view>
		<view class="wrapper">
			<uni-forms label-width="200" :model="form" ref="uForm" label-position="left" :rules="rules">
				<view class="column">
					<view class="flag-title fte87722">基础信息</view>
					<uni-forms-item required :border-bottom="false" name="merchant_name" label="商铺名称"><input
							v-model="form.merchant_name" placeholder="请输入商铺名称" /></uni-forms-item>
					<uni-forms-item required :border-bottom="false" name="company_name" label="公司名称"><input
							v-model="form.company_name" placeholder="请输入公司名称" /></uni-forms-item>
					<uni-forms-item required :border-bottom="false" name="merchant_address" label="公司所在地">
						<view class="flex align-center" style="height: 36px;line-height: 36px;" @click="showPicker()">
							<text class="flex-1 ft666666">{{form.merchant_address || '选择'}}</text>
							<uni-icons type="location" size="20" color="#666"></uni-icons>
						</view>
					</uni-forms-item>
					<uni-forms-item required :border-bottom="false" name="detail_address" label="公司详细地址"><input
							v-model="form.detail_address" placeholder="请输入公司详细地址" /></uni-forms-item>
					<uni-forms-item required :border-bottom="false" name="contact_name" label="联系人姓名"><input
							v-model="form.contact_name" placeholder="请输入联系人姓名" /></uni-forms-item>
					<uni-forms-item required :border-bottom="false" name="contact_mobile" label="联系人电话"><input type="number"
							v-model="form.contact_mobile" placeholder="请输入联系人电话" /></uni-forms-item>
					<uni-forms-item :border-bottom="false" name="merchant_img" label="商户图片URL" required>
						<view>
							<u-upload :file-list="merchantimgs" :header="{ 'ba-user-token': storage.getAccessToken(),server:true }"
								:action="action" width="200" @on-uploaded="onUploaded($event, 'merchant_img')" :max-count="1"
								:show-progress="false"></u-upload>

							<view class="tips">
								请压缩图片在2M以内，确保文字清晰以免上传或审核失败
							</view>
						</view>
					</uni-forms-item>
				</view>
				<view class="column">
					<view class="flag-title fte87722">营业执照信息</view>
					<uni-forms-item required :border-bottom="false" name="business_list" label="法定经营范围"><input
							v-model="form.business_list" placeholder="请输入法定经营范围" /></uni-forms-item>
					<uni-forms-item :border-bottom="false" name="merchant_licence" label="营业执照电子版" required>
						<view>
							<u-upload :file-list="licencePhotoFileList"
								:header="{ 'ba-user-token': storage.getAccessToken(),server:true }" :action="action" width="200"
								@on-uploaded="onUploaded($event, 'merchant_licence')" :max-count="1" :show-progress="false"></u-upload>

							<view class="tips">
								请压缩图片在2M以内，确保文字清晰以免上传或审核失败
							</view>
						</view>
					</uni-forms-item>
					<uni-forms-item :border-bottom="false" name="official_seal" label="印章图片" required>
						<view>
							<u-upload :file-list="official_seals" :header="{ 'ba-user-token': storage.getAccessToken(),server:true }"
								:action="action" width="200" @on-uploaded="onUploaded($event, 'official_seal')" :max-count="1"
								:show-progress="false"></u-upload>

							<view class="tips">
								请压缩图片在2M以内，确保文字清晰以免上传或审核失败
							</view>
						</view>
					</uni-forms-item>
				</view>
			</uni-forms>
			<view class="submit bge87722cc" @click="validatorStep1Form">
				提交
			</view>
			<m-city :provinceData="list" headTitle="区域选择" ref="cityPicker" @funcValue="getPickerParentValue" pickerSize="4">
			</m-city>
		</view>

		<uniMap v-if="mapFlag" @close="closeMap" @callback="callBackAddress" />
	</view>
</template>

<script>
	import {
		merchantManageauditStatus,
		merchantManageinfo,
		merchantManageapply,
		merchantManageinfoedit
	} from "@/api/entry";

	import city from "@/components/m-city/m-city.vue";
	import storage from "@/utils/storage.js";
	import {
		upload,
		getRegionsById
	} from "@/api/common.js";
	import * as RegExp from "@/utils/RegExp.js";
	import config from '@/config/api.js'
	import uniMap from "@/components/uniMap";
	export default {
		components: {
			"m-city": city,
			uniMap
		},
		data() {
			return {
				companyData: {},
				current: 1,
				auditText: '',
				status: null,
				storage,
				action: upload, //图片上传数据
				defaultInputStyle: {
					background: "#f7f7f7",
					padding: "0 20rpx",
					lineHeight: '36px',
					height: '36px',
					"border-radius": "10rpx",
				},
				licencePhotoFileList: [],
				form: {
					merchant_name: '',
					company_name: '',
					merchant_address: '',
					detail_address: '',
					contact_name: '',
					contact_mobile: '',
					merchant_img: [],
					business_list: '',
					merchant_licence: '',
					latitude: '',
					longitude: '',
					official_seal: ''
				},
				merchantimgs: [],
				official_seals: [],
				list: [{
					id: "",
					localName: "请选择",
					children: [],
				}, ],
				rules: {
					// 验证规则
					merchant_name: [{
						required: true,
						message: "请填写商铺名称"
					}],
					// 验证规则
					company_name: [{
						required: true,
						message: "请填写公司名称"
					}],
					merchant_address: [{
						required: true,
						message: "请选择公司所在地"
					}],
					detail_address: [{
						required: true,
						message: "请填写公司详细地址"
					}],
					contact_name: [{
						required: true,
						message: "请填写联系人姓名"
					}],
					contact_mobile: [{
							required: true,
							message: "请填写联系人电话"
						},
						{
							// 自定义验证函数，见上说明
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// this.$u.test.mobile()就是返回true或者false的
								return this.$u.test.mobile(value);
							},
							message: "手机号码不正确",
							// 触发器可以同时用blur和change
							trigger: ["change", "blur"],
						},
					],
					business_list: [{
						required: true,
						message: "请填写营业执照所示经营范围"
					}],
					merchant_licence: [{
						required: true,
						message: "请上传营业执照"
					}]

				},
				areaTree: [],
				mapFlag: false
			};
		},
		watch: {
			companyData: {
				handler(val) {
					console.log('val', val)
					const obj = {
						...val
					}
					this.$set(this, "form", obj);
					if (val.id) {
						this.merchantimgs = [{
							url: val.merchant_img.includes('http') ? val.merchant_img : config.img + val.merchant_img
						}]
						this.licencePhotoFileList = [{
							url: val.merchant_licence.includes('http') ? val.merchant_licence : config.img + val.merchant_licence
						}]
						this.official_seals = [{
							url: val.official_seal.includes('http') ? val.official_seal : config.img + val.official_seal
						}]
						this.form.merchant_address = obj.merchant_address
						//#ifdef H5
						this.$nextTick(() => {
							this.getRegionsById()
						})
						//#endif
					}
					console.log(this.form, this.merchantimgs)
				},
				deep: true,
				immediate: true
			},
		},
		mounted() {
			this.merchantManageauditStatus()
			this.merchantManageinfo()
		},
		methods: {
			// 关闭地图
			closeMap() {
				this.mapFlag = false;
			},
			// 打开地图并访问权限
			clickUniMap() {
				// #ifndef APP-PLUS
				this.mapFlag = true;
				// #endif
			},

			// 如果拒绝权限 提示区设置
			refuseMap() {
				uni.showModal({
					title: "温馨提示",
					content: "您已拒绝定位,请开启",
					confirmText: "去设置",
					success(res) {
						if (res.confirm) {
							//打开授权设置
							// #ifndef MP-WEIXIN
							uni.getSystemInfo({
								success(res) {
									if (res.platform == "ios") {
										//IOS
										plus.runtime.openURL("app-settings://");
									} else if (res.platform == "android") {
										//安卓
										let main = plus.android.runtimeMainActivity();
										let Intent = plus.android.importClass(
											"android.content.Intent"
										);
										let mIntent = new Intent("android.settings.ACTION_SETTINGS");
										main.startActivity(mIntent);
									}
								},
							});
							// #endif
						}
					},
				});
			},
			// 选择地址后数据的回调
			callBackAddress(val) {
				console.log(val)
				uni.showLoading({
					title: "加载中",
				});
				if (val.address_component && val) {
					this.form.latitude = val.location.lat; //纬度
					this.form.longitude = val.location.lng; //经度
					this.form.merchant_address =
						`${val.address_component.province},${val.address_component.city},${val.address_component.district}`
					this.form.detail_address = val.formatted_addresses.recommend
					uni.hideLoading();
				}
				this.mapFlag = !this.mapFlag; //关闭地图
			},
			merchantManageauditStatus() {
				merchantManageauditStatus().then(res => {
					const data = res.data
					if (data) {
						this.status = data.audit_status
						if (data.audit_status === 0) {
							this.auditText = '您的商户资质正在审核中，请耐心等待审核结果。'
						}
						if (data.audit_status === 2) {
							this.auditText = '您的商户资质审核被拒绝，请联系客服。'
						}
					}

				})
			},
			merchantManageinfo() {
				merchantManageinfo().then(res => {
					if (res.data) {
						this.companyData = res.data.merchant
					}

				})
			},
			getRegionsById() {
				this.areaTree = uni.getStorageSync('areaTree') || []
				// if (this.form.merchant_address) {
				// 	const ids = this.form.merchant_address.split(',')
				// 	const areaFlat = this.flattenAreaTreeRecursive(this.areaTree);
				// 	const pathStr = areaFlat.filter(a => ids.includes(a.value + '')).map(a => a.label).join(
				// 		',')
				// 	this.form.merchant_address = pathStr
				// }
			},
			flattenAreaTreeRecursive(tree, result = [], parentId = null) {
				// 遍历当前层级的每个节点
				tree.forEach(node => {
					// 复制节点并添加父级ID（可选）
					const item = {
						...node,
						parentId
					};
					// 添加到结果数组
					result.push(item);

					// 如果有子节点，递归处理
					if (node.children && node.children.length > 0) {
						this.flattenAreaTreeRecursive(node.children, result, node.value);
					}
				});

				return result;
			},
			// 图片上传
			onUploaded(lists, key) {
				let images = [];
				if (!this.form[key]) {
					this.form[key] = [];
				}
				console.log(lists, key, this.form[key])
				lists.forEach((item) => {
					images.push(item.response.data.file.url);
				});
				this.form[key] = images[0]
			},
			getPickerParentValue(e) {
				let name = "";
				e.forEach((item, index) => {
					if (item.value) {
						// 遍历数据
						if (index == e.length - 1) {
							name += item.localName;
						} else {
							name += item.localName + ",";
						}
					}
				});
				this.form.merchant_address = name;
			},
			// 显示三级地址联动
			showPicker() {
				//#ifdef H5 
				console.log(this.$refs)
				this.$refs.cityPicker.show(this.areaTree);
				//#endif

				//#ifndef H5
				this.clickUniMap()
				//#endif
			},
			validatorStep1Form() {
				// if (this.status === 0 || this.status === 1) return
				this.$refs.uForm.validate(async (valid) => {
					console.log(valid);
					const params = {
						...this.form
					};
					params.merchant_address = params.merchant_address.toString();
					params.merchant_licence = params.merchant_licence.toString();
					params.merchant_img = params.merchant_img.toString();
					params.official_seal = params.official_seal.toString();

					console.log(params)
					if (this.status === 0) return;
					if (params.id) {
						this.merchantManageinfoedit(params)
						return
					}
					const res = await merchantManageapply(params);
					if (res.code === 1) {
						uni.showToast({
							title: "提交成功!",
							icon: "none",
						});
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				});
			},
			merchantManageinfoedit(params) {
				merchantManageinfoedit(params).then(res => {
					if (res.code === 1) {
						uni.showToast({
							title: "提交成功!",
							icon: "none",
						});
						setTimeout(() => {
							uni.navigateBack()
						}, 1500)
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none'
						})
					}
				})
			}
		},
	};
</script>

<style lang="scss" scoped>
	@import './entry.scss';

	/deep/ .uni-forms-item__label {
		width: 104px;
	}

	.column {
		padding: 32rpx;
		margin-bottom: 20rpx;
		background: #fff;
	}

	.submit {
		color: #fff;
		margin-top: 120rpx;
	}

	.tips {
		color: #999;
		font-size: 24rpx;
		line-height: 1.2;
		margin-top: 10rpx;
	}
</style>